<template>
  <div class="storage-application">
    <h3 class="ac">高企入库申请，供被认定为高新技术企业的企业人员提交申请</h3>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="高企认定通过文件" prop="passDoc">
        <el-upload
          ref="applicationFormUpload"
          :on-remove="handleApplicationFormRemove"
          :on-change="handleApplicationFormChange"
          :limit="1"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传pdf文件</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="高企认定通过证书" prop="certificate">
        <el-upload
          :limit="1"
          list-type="picture-card"
          :on-preview="handlePicturePreview"
          :auto-upload="false"
          :on-exceed="handleCertificateExceed"
          :on-change="handleCertificateChange"
          :on-remove="handleCertificateRemove"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传图片，大小不能超过2MB，只能一张</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="isSubmit" type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
    <!-- 预览图片 -->
    <el-dialog v-model="dialogVisible">
      <img
        w-full
        style="max-width: 100%; object-fit: contain"
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ElMessage,
  type FormInstance,
  type UploadFile,
  type UploadInstance,
  type UploadProps,
  type UploadRawFile,
} from 'element-plus';
import { nextTick, onMounted, ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { uploadFile } from '@/api/file';
import { storageApplication, storageApplicationList } from '@/api/enterpeise';
import { getEnterpriseId } from '@/utils/storage';
import { reqFeedback } from '@/utils/reqFeedback';
import { useRouter } from 'vue-router';

// 判断是否提交了高企入库申请
const isSubmit = ref(false);
onMounted(() => {
  const eId = getEnterpriseId();
  // 如果eId存在，则是企业人员，否则，是管理员
  if (eId) {
    storageApplicationList({ enterpriseId: eId }).then((res: any) => {
      if (res.code === 200) {
        if (res.data.total > 0) {
          isSubmit.value = true;
          ElMessage.warning('您已提交入库申请，不能再次提交');
        }
      }
    });
  } else {
    // isSubmit.value = true;
    ElMessage.warning('管理员无需提交入库申请');
  }
});

const form = ref<any>({
  passDoc: null as UploadRawFile | null,
  certificate: null as UploadRawFile | null,
});
const formRef = ref<FormInstance>();

const rules = ref({
  passDoc: [{ required: true, message: '请上传高企认定通过文件' }],
  certificate: [{ required: true, message: '请上传高企认定通过证书' }],
});
// 上传高企认定通过文件
const handleApplicationFormRemove = (file: UploadFile) => {
  form.value.passDoc = null;
};
const applicationFormUpload = ref<UploadInstance>();
const handleApplicationFormChange = (file: UploadFile) => {
  const isPDF = file.raw!.type === 'application/pdf';
  if (!isPDF) {
    applicationFormUpload.value!.clearFiles();
    ElMessage.error('只能上传pdf文件');
    return isPDF;
  }
  if (file.raw) {
    form.value.passDoc = file.raw;
  }
  nextTick(() => {
    formRef.value?.validateField('passDoc');
  });
};

// 上传高企认定证书
const handleCertificateRemove = () => {
  form.value.certificate = null;
};
const handleCertificateExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.error('高企认定通过证书只能上传一张');
};
const handleCertificateChange = (file: UploadFile) => {
  const isValid = validateImage(file);
  if (!isValid) {
    return;
  }
  if (file.raw) {
    form.value.certificate = file.raw;
  }
  nextTick(() => {
    formRef.value?.validateField('certificate');
  });
};

// 校验上传的图片格式
const validateImage = (file: UploadFile) => {
  const isImage = file.raw!.type.startsWith('image/');
  const isLt2M = file.raw!.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('只能上传的图片类型的文件');
    return isImage;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
    return isLt2M;
  }
  return isImage && isLt2M;
};

// 预览图片
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const handlePicturePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const router = useRouter();
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      // 获取企业信息
      const requestData: any = {};
      // 上传高企认定通过文件
      if (form.value.passDoc) {
        const formData = new FormData();
        formData.append('file', form.value.passDoc);
        const res: any = await uploadFile(formData);
        if (res.code === 200) {
          requestData.highTechEnterpriseNotice = res.data.url;
        }
      }
      // 上传高企认定通过证书
      if (form.value.certificate) {
        const formData = new FormData();
        formData.append('file', form.value.certificate);
        const res: any = await uploadFile(formData);
        if (res.code === 200) {
          requestData.highTechEnterpriseCertificate = res.data.url;
        }
      }
      storageApplication(requestData).then((res: any) => {
        reqFeedback(res, '提交成功');
        if (res.code === 200) {
          router.replace({
            name: 'personalCenterStorageApplication',
          });
        }
      });
    }
  });
};
</script>

<style scoped lang="scss">
.storage-application {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .el-form {
    width: 50%;
    margin-top: 50px;
  }
}
</style>
